package com.niuwa.p2p.service.impl.productTemplate;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.niuwa.p2p.core.utils.DictConstant;
import com.niuwa.p2p.dao.productTemplate.ProdPropertyDao;
import com.niuwa.p2p.dao.productTemplate.ProductTemplateDao;
import com.niuwa.p2p.dao.productTemplate.TempPropConfigDao;
import com.niuwa.p2p.dao.productTemplate.TemplateAuditDao;
import com.niuwa.p2p.dao.productTemplate.TemplateProtocolDao;
import com.niuwa.p2p.dao.protocol.ProtocolDao;
import com.niuwa.p2p.entity.productTemplate.ProductProperty;
import com.niuwa.p2p.entity.productTemplate.ProductProtocol;
import com.niuwa.p2p.entity.productTemplate.ProductTemplate;
import com.niuwa.p2p.entity.productTemplate.TempPropConfig;
import com.niuwa.p2p.entity.productTemplate.TemplateAudit;
import com.niuwa.p2p.entity.productTemplate.TemplateProtocol;
import com.niuwa.p2p.service.productTemplate.ITransProdTemplateService;
import com.niuwa.p2p.service.sequence.ISequenceService;
import com.niuwa.p2p.vo.productTemplate.TransProdTmptForm;
import com.niuwa.p2p.vo.productTemplate.TransProdTmptVo;

@Service
public class TransProdTemplateServiceImpl implements ITransProdTemplateService {

	@Autowired
	private ISequenceService sequenceService;

	@Autowired
	private ProductTemplateDao productTemplateDao;

	@Autowired
	private ProdPropertyDao prodPropertyDao;

	@Autowired
	private TempPropConfigDao tempPropConfigDao;

	@Autowired
	private TemplateProtocolDao templateProtocolDao;

	@Autowired
	private TemplateAuditDao templateAuditDao;
	
	@Autowired
	private ProtocolDao protocolDao;

	@Override
	public void addTransProductTmplt(long userId, TransProdTmptForm form)
			throws Exception {

		// 保存产品模板基本信息（p2p_product_template）
		ProductTemplate pt = new ProductTemplate();
		pt.setTempName(form.getTempName());
		pt.setTempCode(sequenceService.getCompleteSequenceBySeqKey("MBZR")); // 从数据库中获取
		pt.setMainVersion(Integer.parseInt(form.getMainVersion()));
		pt.setMinorVersion(Integer.parseInt(form.getMinorVersion()));
		pt.setTempStatus(DictConstant.TempStatus.WAIT.getCode()); // 待审核
		pt.setTempType(DictConstant.ProdTemplateType.TRANSFER.getCode()); // 投资产品模板
		pt.setProdCount(0); // 初始关联未到期产品的个数为0
		pt.setOperator(userId);
		pt.setActiveTime(form.getActiveTime());
		pt.setCreateTime(new Date());
		pt.setDelFlag("N"); // 初始值：不是删除标识
		productTemplateDao.addProductTemplate(pt);

		long tempId = pt.getTempId();

		// 保存产品属性（1、基本信息，2、区间信息）（p2p_temp_prop_config和p2p_area_prop_cfg表）
		this.addTempPropConfig(tempId, form); // 新增产品属性列表

		// 保存产品模与产品协议对应信息（p2p_template_protocol）
		if (null != form.getProtId() && form.getProtId().length > 0)
			this.addTemplateProtocol(tempId, form);

		// 保存模板审核信息（p2p_template_audit）
		TemplateAudit ta = new TemplateAudit();
		ta.setTempId(tempId);
		ta.setOperateType(DictConstant.TempStatus.WAIT.getCode());
		ta.setRemark("借款产品模板提交审核");
		ta.setOperator(userId);
		templateAuditDao.insertTemplateAudit(ta);
	}

	@Override
	public TransProdTmptVo getProdTmptById(long tempId) {
		
		TransProdTmptVo lptv = new TransProdTmptVo();

		TransProdTmptForm iptf = new TransProdTmptForm();

		// 获取产品模板基本信息
		ProductTemplate pt = productTemplateDao.selectByTempId(tempId);
		iptf.setTempCode(pt.getTempCode());
		iptf.setTempName(pt.getTempName());
		iptf.setMainVersion(String.valueOf(pt.getMainVersion()));
		iptf.setMinorVersion(String.valueOf(pt.getMinorVersion() + 1));
		iptf.setActiveTime(pt.getActiveTime());
		iptf.setTempId(pt.getTempId());

		// 获取产品属性列表信息
		List<TempPropConfig> tpcList = tempPropConfigDao
				.getTpcListByTempId(tempId);
		for (TempPropConfig tpc : tpcList) {
			// 设置属性值和设置类型
			this.setTransProdTmptForm(tpc, iptf);
		}
		lptv.setTmptForm(iptf);

		// 获取协议信息
		List<ProductProtocol> ppList = protocolDao.getPpListByTempId(tempId);
		lptv.setPpList(ppList);

		return lptv;
	}
	
	/**
	 * 设置产品属性
	 * 
	 * @param tpc
	 * @param iptf
	 */
	private void setTransProdTmptForm(TempPropConfig tpc, TransProdTmptForm iptf) {

		String propCode = tpc.getPropCode();
		String propValue = tpc.getPropValue();
		String setType = tpc.getSetType();

		Class<TransProdTmptForm> classz = TransProdTmptForm.class;
		Method[] methods = classz.getDeclaredMethods();
		try {
			for (Method method : methods) {
				String name = method.getName();
				method.setAccessible(true);
				if (("set" + propCode).equals(name)) { // set普通属性
					method.invoke(iptf, propValue);
				}
				if (("setSETYPE_" + propCode).equals(name)) {
					method.invoke(iptf, setType);
				}
			}
		} catch (IllegalAccessException | IllegalArgumentException
				| InvocationTargetException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 新增选中的协议信息列表
	 * 
	 * @param tempId
	 * @param form
	 */
	private void addTemplateProtocol(long tempId, TransProdTmptForm form) {
		String[] pids = form.getProtId();
		List<TemplateProtocol> tpList = new ArrayList<TemplateProtocol>();
		for (int index = 0; index < pids.length; index++) {
			TemplateProtocol tp = new TemplateProtocol();
			tp.setTempId(tempId);
			if (null != pids[index] && !"".equals(pids[index]))
				tp.setProtId(Long.valueOf(pids[index]));
			tpList.add(tp);
		}
		templateProtocolDao.addTemplateProtocol(tpList);
	}

	/**
	 * 新增产品模板
	 * 
	 * @param tempId
	 *            产品模板ID
	 * @param form
	 */
	private void addTempPropConfig(long tempId, TransProdTmptForm form) {

		// 产品属性表
		List<ProductProperty> ppList = prodPropertyDao
				.searchAll(DictConstant.ProdTemplateType.TRANSFER.getCode());

		List<TempPropConfig> tpcList = new ArrayList<TempPropConfig>();

		for (ProductProperty pp : ppList) {
			String propCode = pp.getPropCode();
			String propValue = this.getPropValue("", propCode, form);

			TempPropConfig tpc = new TempPropConfig();
			tpc.setTempId(tempId);
			tpc.setPropName(pp.getPropName());
			tpc.setPropCode(propCode);
			tpc.setPropValue(propValue);
			tpc.setSetType(this.getPropValue("SETYPE_", propCode, form));
			tpc.setIsAreaProp("N"); // 不是区间属性
			tpcList.add(tpc);
		}
		tempPropConfigDao.addTempPropConfig(tpcList);
	}

	/**
	 * 循环读取页面上的值
	 * 
	 * @param propCode
	 * @param form
	 * @return String
	 */
	private String getPropValue(String prefix, String propCode,
			TransProdTmptForm form) {
		Object result = null;
		Object[] args = new Object[] {};
		String methodName = "get" + prefix + propCode;
		try {
			Method[] methods = form.getClass().getMethods();
			for (Method method : methods) {
				if (methodName.equals(method.getName())) {
					result = method.invoke(form, args);
				}
			}
		} catch (IllegalAccessException | IllegalArgumentException
				| InvocationTargetException e) {
			e.printStackTrace();
		}
		return null == result ? "" : result.toString();
	}
}
